/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-08-09
 * Time: 23:52
 */
public class Solution {
     public boolean canPlaceFlowers1(int[] flowerbed, int n) {
         int len = flowerbed.length;
         int count = 0;
         for (int i = 0;i < len;i++) {
             // 这个位置为 0
             if (flowerbed[i] == 0) {
                 // 前面没有或者前面为 0
                 if (i == 0 || flowerbed[i-1] == 0) {
                     // 后面没有 或者后面为 0
                     if (i == len-1 || flowerbed[i+1] == 0) {
                         i++;
                         count++;
                     }
                 }
             }
         }
         return count >= n;
     }

    public boolean canPlaceFlowers(int[] flowerbed, int n) {
        int count = 0;
        int m = flowerbed.length;
        int prev = -1;
        for (int i = 0; i < m; i++) {
            if (flowerbed[i] == 1) {
                // 计算两个 1 之间的举例, 从而直接得出两个 1 之间能中几个话花
                // 注意第一个即为 0
                if (prev < 0) {
                    count += i / 2;
                } else {
                    count += (i - prev - 2) / 2;
                }
                // 当结果 >= n 时直接返回
                if (count >= n) {
                    return true;
                }
                prev = i;
            }
        }
        // 全部是 0
        if (prev < 0) {
            count += (m + 1) / 2;
        } else {
            count += (m - prev - 1) / 2;
        }
        return count >= n;
    }
}
